const app = getApp()
Page({
	data: {
		emotionUrl: '',
		previewImageTagWidth: 0,
		previewImageTagHeight:0,
		allText: [],
		isTextEdit: false,
		isChooseFontSize: false,
		isChooseFontColor: false,
		isChooseFontPattern: false,
		inputFocus: false,
		texted: false,
		allColor: ['#000000', '#7f7f7f', '#880015', '#ed1c24', '#ff7f27', '#fff200', '#22b14c', '#00a2e8', '#ffaec9', '#a349a4', '#ffffff', '#c3c3c3'],
		tempImageSrc: ''
	},
	onLoad: function (option) {
		var self = this
		this.device = app.globalData.myDevice
		this.deviceRatio = this.device.windowWidth / 750
		console.log(option.url)
		this.setData({
			emotionUrl: option.url || "../../images/pander.jpg"
		})

		const query = wx.createSelectorQuery()
		query.select('#tempCanvas')
			.fields({ node: true, size: true })
			.exec(res => {
				let canvas = res[0].node
				//console.log(canvas)
				let dpr = self.deviceRatio
				self.canvas = canvas
				//canvas.width = 400 * dpr
				//canvas.height = 400 * dpr
				//canvas.getContext('2d').scale(dpr, dpr)
			})
	},

	/**
	 * 预览图加载完毕
	 * @param {object} event 
	 */
	onPrevieImageLoad:function(event){
		const MAX_WIDTH = 650
		const MAX_HEIGHT = 650
		var width = event.detail.width / this.deviceRatio
		var height = event.detail.height / this.deviceRatio

		// 限制宽高
		width = width>MAX_WIDTH ? MAX_WIDTH:width
		height = height>MAX_HEIGHT ? MAX_HEIGHT:height

		this.setData({
			previewImageTagWidth:width,
			previewImageTagHeight:height
		})
	},

	/**
	 * [添加文字按钮被点击]
	 */
	onTouchAddText() {
		var allText = this.data.allText
		allText.push({
			idx: allText.length - 1,
			someText: "点我输入文字",
			fontColor: this.fontColor ? this.fontColor : 'rgba(20,20,20,0.8)',
			fontSize: this.fontSize ? this.fontSize : 14,
			fontStyle: 'normal',
			fontWeight: 'normal',
			textL: 285 * this.deviceRatio,   //rpx, left
			textT: 420 * this.deviceRatio,  // right
			isTextActive: true,
		})
		this.setData({
			isTextEdit: true,
			allText: allText,
			isChooseFontSize: false,
			isChooseFontColor: false,
			isChooseFontPattern: false
		})
	},

	/**
	 * Text tag 被点击,获得焦点
	 * 让对应Input控件 获得\失去焦点
	 */
	onTouchTextTag() {
		this.setData({
			inputFocus: !this.data.inputFocus,
		})
	},

	/**
	 * 文本控件输入框 Input 输入文字事件
	 */
	onInputText(e) {
		var allText = this.data.allText
		allText[allText.length - 1].someText = e.detail.value
		if (allText[allText.length - 1].someText.length == 0) {
			allText[allText.length - 1].someText = "点击输入文字"
		}
		this.setData({
			allText: allText
		})
	},

	/**
	 * 触摸Text控件 开始
	 * @param {object} e 
	 */
	onTextMoveStart(e) {
		this.textX = e.touches[0].clientX
		this.textY = e.touches[0].clientY
	},

	/**
	 * 触摸Text控件 移动
	 */
	onTextMove(e) {
		var allText = this.data.allText
		var dx = (e.touches[0].clientX - this.textX)
		var dy = (e.touches[0].clientY - this.textY)
		var minTextL = 0
		var minTextT = 0
		var maxTextL = 750 * this.deviceRatio - 50
		var maxTextT = 1000 * this.deviceRatio - 50
		var newTextL = allText[allText.length - 1].textL + dx
		var newTextT = allText[allText.length - 1].textT + dy
		if (newTextL < minTextL) newTextL = minTextL
		if (newTextL > maxTextL) newTextL = maxTextL
		if (newTextT < minTextT) newTextT = minTextT
		if (newTextT > maxTextT) newTextT = maxTextT

		allText[allText.length - 1].textL = newTextL
		allText[allText.length - 1].textT = newTextT
		this.setData({
			allText: allText,
			isChooseFontSize: false,
			isChooseFontColor: false,
			isChooseFontPattern: false
		})
		this.textX = e.touches[0].clientX
		this.textY = e.touches[0].clientY
	},

	onTouchChooseFontsize() {
		this.setData({
			isChooseFontSize: !this.data.isChooseFontSize,
			isChooseFontColor: false,
			isChooseFontPattern: false
		})
	},
	/**
	 * 滑条滑动
	 * @param {object} e
	 */
	onFontsizeSliderChange(e) {
		this.fontSize = e.detail.value
		var allText = this.data.allText
		if (allText[allText.length - 1] && (allText[allText.length - 1].isTextActive)) {
			allText[allText.length - 1].fontSize = this.fontSize
			this.setData({
				allText: allText
			})
		}
		// this.setData({
		//   isEraser: false
		// })
	},

	onTouchChooseFontColor() {
		this.setData({
			isChooseFontSize: false,
			isChooseFontColor: !this.data.isChooseFontColor,
			isChooseFontPattern: false
		})
	},
	/**
	 * 颜色table view 项目被点击
	 * @param {object} e 
	 */
	onFontColorChange(e) {
		this.fontColor = e.target.dataset.selected
		var allText = this.data.allText
		if (allText[allText.length - 1] && (allText[allText.length - 1].isTextActive)) {
			allText[allText.length - 1].fontColor = this.fontColor
			this.setData({
				allText: allText
			})
		}
	},

	onTouchChooseFontPattern() {
		this.setData({
			isChooseFontSize: false,
			isChooseFontColor: false,
			isChooseFontPattern: !this.data.isChooseFontPattern
		})
	},
	onFontStyleChange(e) {
		this.fontStyle = e.detail.value ? 'oblique' : 'normal'
		var allText = this.data.allText
		if (allText[allText.length - 1] && (allText[allText.length - 1].isTextActive)) {
			allText[allText.length - 1].fontStyle = this.fontStyle
			this.setData({
				allText: allText
			})
		}
	},
	onFontWeightChange(e) {
		this.fontWeight = e.detail.value ? 'bold' : 'normal'
		var allText = this.data.allText
		if (allText[allText.length - 1] && (allText[allText.length - 1].isTextActive)) {
			allText[allText.length - 1].fontWeight = this.fontWeight
			this.setData({
				allText: allText
			})
		}
	},

	/**
	 * 取消添加文字
	 */
	onTouchCancelAddText() {
		var allText = this.data.allText
		allText.pop()
		this.setData({
			allText: allText,
			isTextEdit: false,
			inputFocus: false,
			isChooseFontSize: false,
			isChooseFontColor: false,
			isChooseFontPattern: false
		})
	},


	/**
	 * 确认添加文字
	 */
	onTouchConfirmAddText() {
		var self = this
		var allText = this.data.allText
		if (allText[allText.length - 1].someText == "点击输入文字" || allText[allText.length - 1].someText == "") {
			this.cancelAddText()
		}
		else {
			allText[allText.length - 1].isTextActive = false
			this.setData({
				allText: allText,
				isTextEdit: false,
				inputFocus: false,
				isChooseFontSize: false,
				isChooseFontColor: false,
				isChooseFontPattern: false,
				texted: true
			})

			const canvas = self.canvas
			const ctx = canvas.getContext('2d')
			//var img = canvas.createImage()
			//var ctx = wx.createCanvasContext('tempCanvas')
			//console.log('ctx', ctx)
			//self.updateCanvasSize()

			// 计算文字bounding rect
			var query = wx.createSelectorQuery();
			query.selectAll('.compete-text').boundingClientRect();
			query.selectAll('.previewImageTag').boundingClientRect();
			query.exec(function (res) {
				//console.log(res)
				if(res.length < 2){
					return
				}
				var textNodes = res[0]
				var imgNode = res[1][0]
				//console.log('textNode',textNodes[0])
				//console.log('imgNode', imgNode)
				var top = textNodes[0].top, left=textNodes[0].left, right=textNodes[0].right, bottom = textNodes[0].bottom
				// 寻找最小值
				for(let i in textNodes){
					top = top > textNodes[i].top ? textNodes[i].top: top
					left = left > textNodes[i].left ? textNodes[i].left: left
					bottom = bottom > textNodes[i].bottom ? textNodes[i].bottom: bottom
					right = right > textNodes[i].right ? textNodes[i].right: right
				}
				//console.log(self.deviceRatio)
				// 文本边界矩形（相对于左上角)
				var textBoundingRect = [left, top,  right,  bottom]
				//console.log('textBoundingRect', textBoundingRect)
				// 图像边界矩形
				var imgBoundingRect = [imgNode.left, imgNode.top, imgNode.left + imgNode.width, imgNode.top + imgNode.height]
				
				//console.log('imgBoundingRect', imgBoundingRect)
				//TODO:计算最终图像boundary
				// 左上取较小值,右下取较大值
				var boundingRect = [0, 0, 0, 0]
				boundingRect[0] = textBoundingRect[0] < imgBoundingRect[0] ? textBoundingRect[0] : imgBoundingRect[0]
				boundingRect[1] = textBoundingRect[1] < imgBoundingRect[1] ? textBoundingRect[1] : imgBoundingRect[1]
				boundingRect[2] = textBoundingRect[2] > imgBoundingRect[2] ? textBoundingRect[2] : imgBoundingRect[2]
				boundingRect[3] = textBoundingRect[3] > imgBoundingRect[3] ? textBoundingRect[3] : imgBoundingRect[3]

				// 取整数
				// for(var i=0;i<4;i++){
				// 	img
				// }
				//console.log('boundingRect', boundingRect)
				
				// 设置画布输出图像宽高
				self.canvas.width = boundingRect[2] - boundingRect[0]
				self.canvas.height = boundingRect[3] - boundingRect[1]
				// 画背景
				ctx.fillStyle = '#ffffff'
				ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)

				// 画图像
				var img = canvas.createImage()
				
				console.log('img',img)
				img.onload = ()=>{
					ctx.drawImage(img, imgBoundingRect[0] - boundingRect[0], imgBoundingRect[1] - boundingRect[1],
						imgBoundingRect[2]-imgBoundingRect[0], imgBoundingRect[3]-imgBoundingRect[1])
					ctx.textAlign = 'left'
					ctx.textBaseline = 'top'
					var allText = self.data.allText
					for(var i in allText){
						let text = allText[i]
						ctx.fillStyle = text.fontColor
						// ctx.font = "oblique bold 30px sans-serif"
						ctx.font = text.fontStyle + ' ' + text.fontWeight + ' ' + text.fontSize + 'px sans-serif'
						ctx.fillText(text.someText, textNodes[i].left - boundingRect[0], textNodes[i].top - boundingRect[1])
					}
					//保存图片到临时路径
					//console.log('befor draw')
					saveImgUseTempCanvas(self, 200)
				}
				img.src = self.data.tempImageSrc ? self.data.tempImageSrc : self.data.emotionUrl
				
			
			
			//ctx.draw(true)
			//保存图片到临时路径
			//saveImgUseTempCanvas(self, 200)
			//img.src = self.data.tempImageSrc ? self.data.tempImageSrc : self.data.emotionUrl

			}) ;
			

		}
	},

	/**
	 * 保存图片到本地按钮被点击
	 */
	onTouchSaveImage(){
		wx.saveImageToPhotosAlbum({
			filePath: this.data.tempImageSrc ? this.data.tempImageSrc : this.data.emotionUrl,
			success() { 
				console.log('保存成功')
			},
			fail:function(e){
				console.log('保存失败', e)
			}
		  })
	},
	/**
	 * 预览图片按钮被点击
	 */
	onTouchPreview(){
		wx.previewImage({
			urls: [this.data.tempImageSrc ? this.data.tempImageSrc : this.data.emotionUrl] // 需要预览的图片http链接列表
		})
	},
	/**
	 *上传到云端按钮被点击
	 */
	onTouchCloud(){
		//TODO: 上传到云端
	}
})

function saveImgUseTempCanvas(self, delay) {
	//console.log('开始绘制图像')
	setTimeout(function () {
		wx.canvasToTempFilePath({
			canvas: self.canvas,
			//canvasId: 'tempCanvas',
			success: function (res) {

				console.log('成功,路劲为:',res.tempFilePath)
				self.setData({
					tempImageSrc: res.tempFilePath
				})
				self.setData({
					allText:[]
				})
			},
			fail: function (res) {
				console.log('绘制失败')
				console.log(res)
			},
			complete: function () {
				wx.hideLoading();
			}
		})
	}, delay)
}